package com.example.base.fragment;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.base.R;
import com.example.base.adapter.SerachHistoryAdapter;
import com.example.base.adapter.SerachHotAdapter;
import com.example.base.bean.HotOne;
import com.example.base.bean.Question;
import com.example.base.bean.SerachBean;
import com.example.base.sqllite.SerachSQLite;
import com.example.base.view.SysViewLayout;
import com.example.base.view.SysViewLayout2;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;



public class SearchFragment extends Fragment {

  private Context context;
  private SysViewLayout sysViewLayout;
  private SerachHotAdapter serachHotAdapter;
  private SerachHistoryAdapter serachHistoryAdapter;
  private ListView listView;
  private ImageButton img_back;
  private ImageButton img_ser;
  private EditText editText;
  private SysViewLayout2 sysViewLayout2;
  private List<SerachBean> serachBeans;
  private ImageButton img_clear;
  private TextView text_clear;
  private List<HotOne> dataList = new ArrayList<>();

  public SearchFragment() {

  }


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    View inflate = inflater.inflate(R.layout.fragment_serach, container, false);
    initView(inflate);
    initListener();
    sendRequestWithokhttp();
    showsqlite();
    return inflate;
  }


  private void initchiledView(List<SerachBean> serachBeans) {
    LayoutInflater mInflater = LayoutInflater.from(context);
    Random random = new Random();
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(10, 5, 10, 5);
    if (sysViewLayout != null) {
      sysViewLayout.removeAllViews();
    }
    for (int i = 0; i < serachBeans.size(); i++) {
      TextView tv = new TextView(context);
      tv.setPadding(28, 10, 28, 10);
      tv.setText(serachBeans.get(i).getText());
      tv.setMaxEms(10);
      tv.setSingleLine();
      tv.setBackgroundResource(R.drawable.shape_textback);
      tv.setLayoutParams(layoutParams);
      tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          String ser = tv.getText().toString();
          editText.setText(ser);
        }
      });
      sysViewLayout.addView(tv, layoutParams);
    }
  }

  private void showsqlite() {
    SerachSQLite serach = new SerachSQLite(context, "serach", null, 1);
    SQLiteDatabase db = serach.getWritableDatabase();
    String query = "select * from serach";
    Cursor cursor = db.rawQuery(query, null);
    List<SerachBean> dats = new ArrayList<>();
    while (cursor.moveToNext()) {
      SerachBean serachBean = new SerachBean();
      String text = cursor.getString(cursor.getColumnIndex("text"));
      serachBean.setText(text);
      dats.add(serachBean);
    }
    serachBeans = dats;
    initchiledView(serachBeans);
  }


  private void sendRequestWithokhttp() {
    OkHttpClient mOkHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
        .url("https://www.wanandroid.com//hotkey/json")
        .get()
        .build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
      @Override
      public void onFailure(@NotNull Call call, @NotNull IOException e) {
      }

      @Override
      public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        if (response.isSuccessful()) {
          Gson gson = new Gson();
          HotOne hotOne = gson.fromJson(response.body().string(), HotOne.class);
          getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
              initHotView(hotOne);
            }
          });
        }

      }

    });
  }

  private void initHotView(HotOne hotOne) {
    LayoutInflater mInflater = LayoutInflater.from(context);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(10, 5, 10, 5);
    if (sysViewLayout2 != null) {
      sysViewLayout2.removeAllViews();
    }
    for (int i = 0; i < hotOne.getData().size(); i++) {
      TextView tv = new TextView(context);
      tv.setPadding(28, 10, 28, 10);
      tv.setText(hotOne.getData().get(i).getName());
      tv.setMaxEms(10);
      tv.setSingleLine();
      tv.setBackgroundResource(R.drawable.shape_textback);
      tv.setLayoutParams(layoutParams);
      tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          String hotser = tv.getText().toString();
          editText.setText(hotser);
        }
      });
      sysViewLayout2.addView(tv, layoutParams);
    }
  }

  private void initListener() {
    text_clear.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        SerachSQLite serach = new SerachSQLite(context, "serach", null, 1);
        serach.getWritableDatabase().delete("serach", null, null);
        showsqlite();
      }
    });
    img_clear.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        editText.getText().clear();
      }
    });
    img_back.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        getActivity().getSupportFragmentManager().popBackStack();
      }
    });
    img_ser.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String edserach = String.valueOf(editText.getText());
        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {

            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                .add("k", edserach)
                .build();
            Request request = new Request.Builder()
                .url("https://www.wanandroid.com/article/query/0/json")
                .post(body)
                .build();
            Call call = client.newCall(request);
            // 同步或异步请求
            call.enqueue(new Callback() {
              @Override
              public void onFailure(@NotNull Call call, @NotNull IOException e) {
              }

              @Override
              public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                  Gson gson = new Gson();
                  String data = response.body().string();
                  Log.i("Serach", data);
                  Question question = gson.fromJson(data, Question.class);
                  if (question.getData().getDatas() != null && question.getData().getDatas().size() > 0) {
                    ContentValues cv = new ContentValues();
                    cv.put("text", edserach);
                    SerachSQLite serach = new SerachSQLite(context, "serach", null, 1);
                    SQLiteDatabase db = serach.getWritableDatabase();
                    long row = db.insert("serach", null, cv);
                    Log.i("SerachFragment", row + "");
                    db.close();
                    showsqlite();
                    Intent intent = new Intent(context, SearchFragment.class);
                    intent.putExtra("result", data);
                    startActivity(intent);
                  } else {
                    getActivity().runOnUiThread(() -> Toast.makeText(context, "无查询结果", Toast.LENGTH_SHORT).show());

                  }
                }
              }
            });

          }
        });

      }

    });
  }

  private void initView(View inflate) {
    sysViewLayout = inflate.findViewById(R.id.flowlayout);
    sysViewLayout2 = inflate.findViewById(R.id.flowlayout2);
    img_back = inflate.findViewById(R.id.img_system_back);
    img_ser = inflate.findViewById(R.id.img_serach);
    editText = inflate.findViewById(R.id.ed_serach);
    img_clear = inflate.findViewById(R.id.clear_edtext);
    text_clear = inflate.findViewById(R.id.text_clear_his);
    context = getContext();
  }
}